package logic

import (
	"context"
	"errors"
	"login-guard/mysql/cache"
	"login-guard/mysql/models"
	"login-guard/pkg"
	"time"

	"login-guard/loginrpc/internal/svc"
	"login-guard/loginrpc/loginrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginsLogic {
	return &LoginsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginsLogic) Logins(in *loginrpc.LoginsRequest) (*loginrpc.LoginsResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	s2, _ := cache.Rdb.Get(cache.Ctx, "LoginAdd"+in.Password).Int64()
	if s2 >= 2 {
		return nil, errors.New("错误次数过多，请稍后重试")
	}
	err := user.Users(models.DB, in)
	if err != nil {
		return nil, errors.New("用户不存在")
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码错误")
	}
	cache.Rdb.Set(cache.Ctx, "LoginAdd"+in.Password, 2, time.Hour*120)
	s, err := cache.Rdb.Incr(cache.Ctx, "Loginss"+in.Password).Result()
	if s == 2 {
		cache.Rdb.Expire(cache.Ctx, "LoginAdd"+in.Password, time.Hour*120)
		return nil, errors.New("禁止登陆")
	}
	result, err := cache.Rdb.Get(cache.Ctx, "sendSmsAdd"+in.Username).Result()
	if result != in.SendSms {
		return nil, errors.New("短信发送失败")
	}

	return &loginrpc.LoginsResponse{
		UserId: int64(user.ID),
	}, nil
}
